import $global from '@/module/tipsGroup'
export default {
  methods: {
    getLocation (leaderObj) {
      const _that = this
      return new Promise((resolve, reject) => {
        uni.getSystemInfo({
          success (res) {
            console.log("判断手机定位服务是否授权:", res);
            let locationEnabled = res.locationEnabled; //判断手机定位服务是否开启
            let locationAuthorized = res.locationAuthorized;
            if (locationEnabled == false || locationAuthorized == false) {
              //手机定位服务（GPS）未授权
              $global.$toast('error', '请打开手机GPS')
            } else {
              uni.authorize({
                //授权请求窗口
                scope: "scope.userLocation", //授权的类型
                success (res) {
                  $global.$loading()
                  _that.fnGetlocation(leaderObj, resolve, reject);
                },
                fail (res) {
                  $global.$hiding()
                  $global.$toast('error', '授权失败！')
                  console.log('授权失败', res);
                  reject()
                }
              })
            }
          },
          fail () {
            reject()
          }
        })
      })
    },
    fnGetlocation (leaderObj, resolve, reject) {
      const _that = this
      uni.getLocation({
        type: 'wgs84',
        isHighAccuracy: "true",
        accuracy: "best",
        success: (res) => {
          console.log('成功', res);
          let platform = uni.getSystemInfoSync().platform;
          console.log('platform===>', platform);
          const bindList = {}
          if (platform == "ios") {
            //toFixed() 方法可把 Number 四舍五入为指定小数位数的数字。
            bindList.long = res.longitude.toFixed(6);
            bindList.lat = res.latitude.toFixed(6);
          } else {
            bindList.long = res.longitude;
            bindList.lat = res.latitude;
          }
          const distance = _that.getDistance(bindList.lat, bindList.long, leaderObj.lat, leaderObj.long)
          console.log('定位数据===>', bindList, distance);
          resolve(distance)
        },
        fail: (res) => {
          console.log('失败', res);
          reject()
        },
        complete () {
          $global.$hiding()
        }
      })
    },
    getDistance (lat1, lng1, lat2, lng2) {
      // lat2 = 30
      // lng2 = 120
      lat1 = lat1 || 0;
      lng1 = lng1 || 0;
      lat2 = lat2 || 0;
      lng2 = lng2 || 0;

      let rad1 = lat1 * Math.PI / 180.0;
      let rad2 = lat2 * Math.PI / 180.0;
      let a = rad1 - rad2;
      let b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
      let r = 6378.137; // 输出为公里
      let distance = r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2), 2)));
      return distance;
    }
  }
}